<?php

namespace pc\models;

use common\helpers\ChineseSpell;
use common\Service\RedisService;
use Yii;
use common\models\Tags as P_Tags;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%tags}}".
 *
 * @property string $id
 * @property string $name
 * @property string $show_name
 * @property string $alias
 * @property string $tags
 * @property integer $type
 * @property string $sort
 * @property integer $status
 */
class Tags extends P_Tags
{

    //普通标签关联女星 标签一步到位
    public function relationGirl(){
        ini_set("max_execution_time",0);
        ini_set("memory_limit", "1024M");
        $tags = Tags::find()->asArray()->orderBy(['type' => SORT_ASC])->where(['<','id',2000])->andWhere(['<','category',2])->all();
//        foreach ($tags as &$tag){
//            $tag['len'] = mb_strlen($tag['name']);
//        }
//        ArrayHelper::multisort($tags,'len',SORT_DESC);  //这个排序用于站内链接
        ///24311
        $redis = Yii::$app->redis;
        for($i = 16667 ; $i < 24311 ; $i++) {
            $starInfo = RedisService::getHash('star:' . $i);
            foreach ($tags as $tag){
                $tagType = intval($tag['type']);

                if($tagType == 0 || $tagType == 2){  //普通标签的类型标签都是内容荣里面提取的
                    if(isset($starInfo['desc']) && stripos($starInfo['desc'],strtolower($tag['name'])) !== false){
                        $redis->ZIncrby('tagZset', 1, strtolower($tag['alias']));
                        $redis->ZAdd('tagZset:' . strtolower($tag['alias']), intval($starInfo['view']), $i);
                    }
                }else if($tagType == 1){   //国家地区
                    if(isset($starInfo['country']) && stripos($starInfo['country'],strtolower($tag['name'])) !== false){
                        $redis->ZIncrby('tagZset', 1, strtolower($tag['alias']));
                        $redis->ZAdd('tagZset:' . strtolower($tag['alias']), intval($starInfo['view']), $i);
                    }
                }else if($tagType == 3){   //职业
                    if(isset($starInfo['job']) && stripos($starInfo['job'],strtolower($tag['name'])) !== false){
                        $redis->ZIncrby('tagZset', 1, strtolower($tag['alias']));
                        $redis->ZAdd('tagZset:' . strtolower($tag['alias']), intval($starInfo['view']), $i);
                    }
                }else if($tagType == 4){ //星座
                    $starSign = [
                        '1' => '白羊座',
                        '2' => '金牛座',
                        '3' => '双子座',
                        '4' => '巨蟹座',
                        '5' => '狮子座',
                        '6' => '处女座',
                        '7' => '天秤座',
                        '8' => '天蝎座',
                        '9' => '射手座',
                        '10' => '魔羯座',
                        '11' => '水瓶座',
                        '12' => '双鱼座',
                    ];
                    if(isset($starInfo['star_sign']) && intval($starInfo['star_sign']) > 0 && $starSign[$starInfo['star_sign']] == $tag['name']){
                        $score = $redis->ZIncrby('tagZset', 1, strtolower($tag['alias']));
                        $redis->ZAdd('tagZset:' . strtolower($tag['alias']), $score, $i);
                    }
                }

            }
        }

    }



    //单独处理星座关系
    public function relationStarSign(){
        $starSign = [
                        '1' => 'aries',
                        '2' => 'taurus',
                        '3' => 'gemini',
                        '4' => 'cancer',
                        '5' => 'leo',
                        '6' => 'virgo',
                        '7' => 'libra',
                        '8' => 'scorpio',
                        '9' => 'sagittarius',
                        '10' => 'capricorn',
                        '11' => 'aquarius',
                        '12' => 'pisces',
                    ];
        $redis = Yii::$app->redis;
        for($i = 16667 ; $i < 24311 ; $i++) {
            $starInfo = RedisService::getHash('star:' . $i);
            if(intval($starInfo['star_sign']) > 0){
                $score = $redis->ZIncrby('tagZset', 1, strtolower($starSign[$starInfo['star_sign']]));
                $redis->ZAdd('tagZset:' . strtolower($starSign[$starInfo['star_sign']]), $score, $i);
            }
        }

    }




    public function updateTagSort(){
        $tagAliases = RedisService::zRange('tagZset');

        foreach ($tagAliases as $alias => $sort){
            $tag = Tags::find()->where(['alias'=>$alias])->one();
            if(!$tag){
                echo $alias;exit;
            }
            $tag->sort = $sort;
            if(!$tag->save()){
                print_r($tag->getErrors());
            }
        }
    }

    //国家标签入库 设置 alias
    public function dealCountryTags(){
        $redis = Yii::$app->redis;
        $countries = RedisService::zRange('M_CountrySSet');
        $chineseSpell = new ChineseSpell();
        foreach ($countries as $country => $sort){
            $pingyin = $chineseSpell->getFullSpell(iconv('UTF-8','GBK',$country));
            $tag = new Tags();
            $tag->name = $country;
            $tag->show_name = '';
            $tag->alias =  strtolower($pingyin);
            $tag->type = 1;
            $tag->status = 1;
            $tag->sort = $sort;
            $tag->save();
            var_dump($tag->getErrors());
        }
    }

    //职业标签入库 设置 alias
    public function dealJobTags(){
        $redis = Yii::$app->redis;
        $jobs = RedisService::zRange('M_JobSSet');
        $chineseSpell = new ChineseSpell();

        $ids = [];
        foreach ($jobs as $job => $sort){
            $pingyin = $chineseSpell->getFullSpell(iconv('UTF-8','GBK',$job));
            $tag = new Tags();
            $tag->name = $job;
            $tag->show_name = '';
            $tag->alias =  strtolower($pingyin);
            $tag->type = 3;
            $tag->sort = 0;
            $tag->status = 1;
            $tag->sort = $sort;
            if(!$tag->save()){
                $ids[] = $job;
            }
        }
        echo implode("','",$ids);
    }


    /**
     * @desc 获取明星列表页面标签菜单
     * @param array $selectedTags 必须展示的标签
     * @return array
     */
    public function starTagMenu($selectedTags = []){
        $menuTags = [];

        $menuTagIds = Yii::$app->get('redis')->Get('starMenuTags'); //读取缓存菜单数据
        if($menuTagIds){
            $menuTagIds = explode(',',$menuTagIds);
            foreach ($menuTagIds as $tagId){
                $tagInfo = static::tagInfoById($tagId);
                $tagInfo && $menuTags[$tagInfo['alias']] = $tagInfo;
            }
        }else{
            //直接数据库中读取数据
            $typeNum = [0 => 10, 1 => 10, 2 => 10, 3 => 10, 4 => 40]; //每个类别对应展示的标签数量
            foreach ($typeNum as $type => $num){
                $temp = Tags::find()
                    ->where(['type' => $type])
                    ->orderBy(['sort' => SORT_DESC])
                    ->limit($num)
                    ->indexBy('alias')
                    ->asArray()
                    ->all();
                $temp && $menuTags = array_merge($menuTags,$temp);
            }
            $menuTagIds = implode(',',array_column($menuTags,'id'));
            Yii::$app->get('redis')->Set('starMenuTags',$menuTagIds);
        }

        $selectTagIds = []; //通过ID来确定 标签是否需要选中
        if(!empty($selectedTags)){ //合并必须展示的标签，进入这个页面的标签可能不是菜单所展示的标签，需要动态加入
            $selectTagIds = array_column($selectedTags,'id');
            $menuTags = array_merge($menuTags,ArrayHelper::index($selectedTags,'alias'));
        }

        $rs = [];
        foreach ($menuTags as $tag){
            $menu['show_name'] = empty($tag['show_name']) ? trim($tag['name']) : trim($tag['show_name']);
            $menu['alias'] = trim($tag['alias']);
            $menu['url'] = $this->createStarTagUrl($tag,$selectedTags);
            $menu['selected'] = in_array($tag['id'],$selectTagIds) ? 1 : 0; //判断是否选中
            $rs[$tag['type']][] = $menu;
        }

        $sortRs = [];
        $typeSort = [1,4,3,2,0]; //列表展示顺序
        foreach ($typeSort as $type){ //排序
            isset($rs[$type]) && $sortRs[$type] = $rs[$type];
        }
        unset($rs);
        return $sortRs;
    }

    /**
     * @desc 创建明星标签链接
     * @param $tag
     * @param $selectedTags 当前标签
     * @return string
     */
    private function createStarTagUrl($tag,$selectedTags){
        if(empty($tag)) return '#';
        if(empty($selectedTags)) return "/meinv/{$tag['alias']}/";
        array_push($selectedTags,$tag);

        $typeAlias = array_column($selectedTags,'alias','type');
        //列表展示顺序 1国家 4星座 3职业 2类型 0普通标签
        $typeSort = [1,4,3,2,0];

        $rs = [];
        foreach ($typeSort as $type){
            isset($typeAlias[$type]) && $rs[$type] = $typeAlias[$type];
        }

        return empty($rs) ? '' : '/meinv/'.implode('-',$rs).'/';
    }


    /**
     * 创建写真标签链接
     * @param $selectedTags
     * @return array
     */
    public function portrayTagMenu($selectedTags){
        $menuTags = [];

        $menuTagIds = Yii::$app->get('redis')->Get('portrayMenuTags'); //读取缓存菜单数据
        if($menuTagIds){
            $menuTagIds = explode(',',$menuTagIds);
            foreach ($menuTagIds as $tagId){
                $tagInfo = static::tagInfoById($tagId);
                $tagInfo && $menuTags[$tagInfo['alias']] = $tagInfo;
            }
        }else{
            //直接数据库中读取数据
            $menuTags = Tags::find()
                ->where(['<>','category',1])
                ->orderBy(['sort' => SORT_DESC])
                ->limit(100)
                ->indexBy('alias')
                ->asArray()
                ->all();

            $menuTagIds = implode(',',array_column($menuTags,'id'));
            Yii::$app->get('redis')->Set('portrayMenuTags',$menuTagIds);
        }

        $selectTagIds = []; //通过ID来确定 标签是否需要选中
        if(!empty($selectedTags)){ //合并必须展示的标签，进入这个页面的标签可能不是菜单所展示的标签，需要动态加入
            $selectTagIds = array_column($selectedTags,'id');
            $menuTags = array_merge($menuTags,ArrayHelper::index($selectedTags,'alias'));
        }

        $rs = [];
        foreach ($menuTags as $tag){
            $menu['show_name'] = empty($tag['show_name']) ? trim($tag['name']) : trim($tag['show_name']);
            $menu['alias'] = trim($tag['alias']);
            $menu['url'] = $this->createStarTagUrl($tag,$selectedTags);
            $menu['url'] = empty($menu['alias']) ? '/xiezhen/' : "/xiezhen/{$menu['alias']}/";
            $menu['selected'] = in_array($tag['id'],$selectTagIds) ? 1 : 0; //判断是否选中
            $rs[] = $menu;
        }

        return $rs;
    }

}
